/**
 * 带重试机制的请求函数
 * @param {Function} requestFn 请求函数
 * @param {number} maxRetries 最大重试次数
 * @param {number} delay 重试延迟时间(ms)
 * @returns {Promise} 请求结果
 */
export async function retryRequest(requestFn, maxRetries = 3, delay = 1000) {
  try {
    return await requestFn()
  } catch (error) {
    if (maxRetries === 0) {
      throw error
    }
    
    // 延迟重试
    await new Promise(resolve => setTimeout(resolve, delay))
    return retryRequest(requestFn, maxRetries - 1, delay)
  }
}

/**
 * 缓存请求结果
 * @param {Object} data 要缓存的数据
 * @param {string} key 缓存键名
 * @param {number} expireTime 过期时间(ms)，默认1小时
 */
export function cacheRequestData(data, key, expireTime = 3600000) {
  const cacheData = {
    data,
    timestamp: Date.now(),
    expireTime
  }
  localStorage.setItem(key, JSON.stringify(cacheData))
}

/**
 * 获取缓存的请求结果
 * @param {string} key 缓存键名
 * @returns {Object|null} 缓存数据或null
 */
export function getCachedRequestData(key) {
  const cached = localStorage.getItem(key)
  if (!cached) return null
  
  const { data, timestamp, expireTime } = JSON.parse(cached)
  if (Date.now() - timestamp > expireTime) {
    localStorage.removeItem(key)
    return null
  }
  
  return data
}

export default {
  retryRequest,
  cacheRequestData,
  getCachedRequestData
} 